<template>
    <!-- 引入子组件，并通过 ref 绑定 -->
    <TeamApply ref="teamApplyRef" />


    <div class="team-management">
        <!-- 标题 -->
        <div class="flex">
            <div class="blue-radius"></div>
            <h2 class="page-title">团队管理</h2>
        </div>

        <!-- 右侧：操作按钮-->
        <el-col class="button-group">
            <el-button type="primary" @click="toAdd()">新增医生团队</el-button>
            <el-button type="primary" style="margin-left: 8px;" @click="toApply()">申请加入团队</el-button>
            <el-button type="success" style="margin-left: 8px;">导出</el-button>
        </el-col>
        <el-row class="tabs-button-row">
            <!-- 左侧：标签页 -->
            <el-col>
                <el-tabs v-model="activeTab" style="font-size: 16px !important;">
                    <el-tab-pane label="我管理的团队" name="1"></el-tab-pane>
                    <el-tab-pane label="我加入的团队" name="2"></el-tab-pane>
                </el-tabs>
            </el-col>
        </el-row>



        <el-row class="filter-bar">
            <!-- 所属机构筛选 -->
            <el-col>
                <!--所属机构标签 -->
                <span class="filter-label">所属机构</span>

                <!-- 选择框 -->
                <el-select v-model="selectedOrg" placeholder="请选择" clearable style="width: 200px; margin-left: 8px;"
                    @change="handleSearch">
                    <el-option v-for="item in orgOptions" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>

                <!-- 输入框 -->
                <el-input v-model="searchKey" placeholder="请输入关键字" clearable
                    style="width: 360px; height: 40px; margin-left: 10px;" @keyup.enter="handleSearch">
                    <template #suffix>
                        <el-icon @click="handleSearch">
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
            </el-col>
        </el-row>



        <!-- 团队列表表格 -->
        <el-table v-loading="loading" :data="teamData" border style="width: 100%"
            @selection-change="handleSelectionChange">
            <!-- 多选框 -->
            <el-table-column type="selection" width="50" align="center"></el-table-column>

            <!-- 编号 -->
            <el-table-column prop="_id" label="编号" align="center"></el-table-column>

            <!-- 头像 -->
            <el-table-column label="头像" align="center">
                <template #default="scope">
                    <el-avatar :src="scope.row.avatar" size="default"></el-avatar>
                </template>
            </el-table-column>

            <!-- 团队名称 -->
            <el-table-column prop="name" label="团队名称" align="center"></el-table-column>

            <!-- 团队长 -->
            <el-table-column prop="leaderId.name" label="团队长" align="center"></el-table-column>

            <!-- 团队标签（多标签展示） -->
            <el-table-column label="团队标签" width="100" align="center">
                <template #default="scope">
                    <el-tag v-for="(tag, index) in scope.row.tagIds" :key="index" size="small"
                        style="margin-right: 5px;">
                        {{ tag.name }}
                    </el-tag>
                </template>
            </el-table-column>

            <!-- 所属机构 -->
            <el-table-column prop="organizationId.name" label="所属机构" align="center" width="160"></el-table-column>

            <!-- 签约人数 -->
            <el-table-column prop="signNumber" label="签约人数" align="center"></el-table-column>

            <!-- 评分 -->
            <el-table-column prop="rate" label="评分" align="center"></el-table-column>

            <!-- 状态（启用/停用开关） -->
            <el-table-column label="状态" align="center">
                <template #default="scope">
                    <el-switch v-model="scope.row.state" :active-value="1" :inactive-value="0" active-text="启用"
                        inactive-text="禁用" @change="handleStatusChange(scope.row)" inline-prompt
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"></el-switch>
                </template>
            </el-table-column>

            <!-- 操作列（查看详情、解散退队） -->
            <el-table-column label="操作" align="center" width="200">
                <template #default="scope">
                    <el-button type="text" icon="el-icon-view" @click="handleView(scope.row._id)"
                        style=" font-weight: 400 !important; font-size: 13px;">查看详情</el-button>
                    <el-button type="text" icon="el-icon-delete"
                        style="color: red; font-weight: 400 !important; font-size: 13px;"
                        @click="deleteTeam(scope.row._id)">解散退队</el-button>
                </template>
            </el-table-column>
        </el-table>


        <!-- 分页 -->
        <el-pagination class="flex-end" v-model:current-page="currentPage" v-model:page-size="pageSize"
            :page-sizes="[5, 10, 15, 20]" :size="size" :background="background" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange"
            layout="total, sizes, prev, pager, next, jumper" /> <!-- 功能的先后顺序 -->

    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessageBox, ElMessage, } from 'element-plus'
import { Search } from '@element-plus/icons-vue' // 引入搜索图标
import { removeTeamsApi, searchTeamsApi, updateTeamsApi } from '../../api/teamManage'
import { useRoute } from 'vue-router';
import { useRouter } from 'vue-router';
import TeamApply from './TeamApply.vue';



const router = useRouter()   //保存跳转路径
const route = useRoute()//保存跳转路径
const orgOptions = ref([])  // 去重后的机构选项
const selectedOrg = ref('') // 选中的所属机构
const searchKey = ref('') // 搜索关键字
const activeTab = ref('1') // 当前激活的标签页
const loading = ref(false) // 表格加载状态
const currentPage = ref(1)       //当前页码
const pageSize = ref(5)          //每页数据条数
const size = ref('default')
const background = ref(true)
const total = ref(0) // 总数据量
// 绑定子组件实例
const teamApplyRef = ref(null);

// 打开申请弹窗的方法（调用子组件暴露的 openDialog）
const toApply = () => {
    teamApplyRef.value?.openDialog();
};



// 表格数据
const teamData = ref([])

// 切换页码 - 实现实际逻辑
const handleSizeChange = (val) => {
    pageSize.value = val;
    findTeamAsync();
}

const handleCurrentChange = (val) => {
    currentPage.value = val;
    findTeamAsync();
}


// 搜索事件
const handleSearch = () => {
    console.log('搜索条件：', selectedOrg.value, searchKey.value)
    currentPage.value = 1; // 搜索时重置为第一页
    findTeamAsync();
}

// 多选事件
const handleSelectionChange = (selectedRows) => {
    console.log('选中的团队：', selectedRows)
}

// 状态切换事件
async function handleStatusChange(update) {
    const res = await updateTeamsApi(update)
    if (res.code == 200) {
        ElMessage({
            type: 'success',
            message: '修改成功'
        })
    } else {
        ElMessage.error(res.message)
    }
    findTeamAsync()
}

// 点击查看详情
const handleView = (_id) => {
    router.push(`/data/team/detail/${_id}`)
    console.log('查看团队详情：', _id)
}

// 点击跳转至增加页面
const toAdd = () => {
    router.push(`/data/team/add`)
}

// 删除功能
async function deleteTeam(_id) {
    try {
        //弹框确认
        await ElMessageBox.confirm(
            '此操作将永久删除此团队，是否继续?',
            '警告❗',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        //调用删除接口
        const res = await removeTeamsApi({ _id });
        if (res.code === 200) {
            ElMessage.success('团队删除成功')
        } else {
            ElMessage.error(res.message || '删除失败')
        }
        //刷新数据
        findTeamAsync();
    } catch (error) {
        ElMessage.info('删除已取消')
    }
}


// 页面加载时模拟请求
onMounted(async () => {
    findTeamAsync();
})


// 监听组件切换,排序,分页切换事件
watch([activeTab, selectedOrg, searchKey, currentPage, pageSize], () => {
    findTeamAsync();
})


// 渲染团队列表 
function findTeamAsync() {
    loading.value = true;
    searchTeamsApi({
        type: activeTab.value,
        doctorId: '686f2fdd0b991e21ee16fc06',
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        organizationId: selectedOrg.value,
        keyword: searchKey.value
    }).then(res => {
        if (res.code === 200) {
            teamData.value = res.data.rows || [];
            total.value = res.data.total || 0; // 从响应中获取总数据量

            // 去重逻辑：提取唯一的 organizationId
            const uniqueOrgs = new Map() // Map 自动去重（_id 作为键）
            teamData.value.forEach(team => {
                const org = team.organizationId
                if (org) { // 防止 organizationId 为 null/undefined
                    uniqueOrgs.set(org._id, org) // 重复的 _id 会被覆盖
                }
            })
            // 格式化为 el-option 需要的结构：{ label, value }
            orgOptions.value = Array.from(uniqueOrgs.values()).map(org => ({
                label: org.name, // 显示名称：organizationId.name
                value: org._id   // 值：organizationId._id（唯一标识）
            }))
        }
    }).catch(error => {
        console.error('获取团队数据失败', error);
        ElMessage.error('获取数据失败');
    }).finally(() => {
        loading.value = false;
    });
}


</script>

<style scoped>
.team-management {
    padding: 20px;
}


.filter-bar {
    margin-bottom: 35px;
}

.filter-label {
    line-height: 32px;
    margin-right: 5px;
    font-size: 14px;
    color: #999;
}

.button-group {
    text-align: right;
}


/* 修改 placeholder 颜色 */
::v-deep .el-input__inner::placeholder {
    color: #ccc;
    /* 浅灰色，可按需调整 */
}
</style>

<style>
.el-table thead {
    color: black !important;
}

.el-table thead th {
    font-weight: 450 !important;
}

.el-table {
    --el-table-border: none !important;
    --el-table-header-bg-color: rgba(242, 242, 242, 0.498039215686275) !important;
    margin-bottom: 20px;
}

.el-main {
    background-color: rgba(242, 247, 251, 1);
}

.team-management {
    background-color: #fff;
}

.tabs-container {
    padding: 0 !important;
}


.page-title {
    margin: 0 0 16px;
    font-size: 18px;
    font-weight: 550;
    color: #333333E5;
}

.blue-radius {
    border-width: 0px;
    width: 6px;
    height: 20px;
    background: inherit;
    background-color: rgba(41, 132, 248, 1);
    border: none;
    border-radius: 8px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    margin-top: 4px;
    margin-right: 10px;
}
</style>